package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.domain.SystemLog;
import cd.cdyb.sms.dto.PageResult;
import cd.cdyb.sms.dto.query.SystemLogQueryDto;
import cd.cdyb.sms.service.SystemLogService;
import cd.cdyb.sms.utils.UserUtils;
import cd.cdyb.sms.dao.SystemLogDao;
import cd.cdyb.sms.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lin
 * @since 2024-04-18
 */
@Service
public class SystemLogServiceImpl implements SystemLogService {

    @Resource
    private SystemLogDao systemLogDao;

    @Override
    public PageResult<SystemLog> findSystemLogPage(SystemLogQueryDto systemLogQueryDto) {
        Page<SystemLog> page = new Page<>(systemLogQueryDto.getPageNo(), systemLogQueryDto.getPageSize());
        LambdaQueryWrapper<SystemLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(SystemLog::getOperatorTime, systemLogQueryDto.getStartTime(), systemLogQueryDto.getEndTime())
                .eq(Objects.nonNull(systemLogQueryDto.getOperatorType()), SystemLog::getOperatorType, systemLogQueryDto.getOperatorType())
                .like(StringUtils.isNotBlank(systemLogQueryDto.getOperatorName()), SystemLog::getOperatorName, systemLogQueryDto.getOperatorName())
                .orderByDesc(SystemLog::getOperatorTime);
        Page<SystemLog> systemLogPage = systemLogDao.selectPage(page, wrapper);
        return new PageResult<>(systemLogQueryDto.getPageNo(), systemLogQueryDto.getPageSize(), systemLogPage.getRecords(), systemLogPage.getTotal());
    }

    @Override
    public void insert(Integer type, String content) throws BusinessException {
        SystemLog systemLog = new SystemLog();
        systemLog.setOperatorType(type);
        systemLog.setContent(content);
        systemLog.setOperatorTime(LocalDateTime.now());
        systemLog.setOperatorId(UserUtils.getCurrentUserId());
        systemLog.setOperatorName(UserUtils.getCurrentName());
        systemLogDao.insert(systemLog);
    }
}
